package com.servlet;

import com.bean.*;

import com.service.HwAttachService;
import com.service.HwService;
import com.service.HwStuService;
import com.service.impl.HwAttachServiceImpl;
import com.service.impl.HwServiceImpl;
import com.utils.DateUtils;
import com.utils.Page;
import com.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static com.utils.Page.PAGE_SIZE;

/**
 * @author Administrator
 */
@WebServlet(name = "HwServlet", urlPatterns = "/HwServlet.do")
public class HwServlet extends BaseServlet {
    HwService hwService = new HwServiceImpl();
    HwAttachService hwAttachService = new HwAttachServiceImpl();

    protected void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String msg = null;
        Map<String, Object> map = new LinkedHashMap<>();
        Map<String, Object> data = new LinkedHashMap<>();
        map.put("code", 0);
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据 得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(request);
                //循环判断 每一个表单项 是普通类型 还是上传的文件
                for (FileItem fileItem : list) {
                    if (!fileItem.isFormField()) {
                        //上传的文件
                        String[] strings = fileItem.getName().split("\\.");
                        String type = "." + strings[strings.length - 1];
                        String imgName = System.currentTimeMillis() + type;
//                        fileItem.write(new File("E:\\hwmanage\\teaFile\\" + imgName));
                        fileItem.write(new File("D:\\Java\\Java2\\hwmanage\\teaFile\\" + imgName));
                        msg = "文件上传成功啦";
                        data.put("fileName", strings[0]);
                        data.put("url", imgName);
                        data.put("type", type);
                    }
                }
            } catch (Exception e) {
                msg = "文件上传失败啦QAQ";
                e.printStackTrace();
            }
        } else {
            msg = "文件上传失败啦QAQ";
        }
        map.put("data", data);
        map.put("msg", msg);
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = null;
        Integer id = Integer.valueOf(request.getParameter("id"));
        HwAttach hwAttach = new HwAttach();
        hwAttach.setHwId(id);
        hwAttach = hwAttachService.selectBy(hwAttach);
        String url = hwAttach.getUrl();
        try {
//            String filePath = "E:\\hwmanage\\teaFile\\" + url;
            String filePath = "D:\\Java\\Java2\\hwmanage\\teaFile\\" + url;
            File file = new File(filePath);
            String FileName = hwAttach.getTitle() + hwAttach.getType();
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(FileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
            outputStream.close();
        }

    }

    protected void page(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        String content = request.getParameter("content");
        Page<Hw> page = hwService.page(pageNo, pageSize, content);
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Teacher teacher = (Teacher) request.getSession().getAttribute("user");
        Hw hw = new Hw();
        HwAttach hwAttach = new HwAttach();
        Map<String, Object> map = new LinkedHashMap<>();
        String msg = "布置作业失败啦！";
        WebUtils.copyParamToBean(request.getParameterMap(), hw);
        hw.setTeacherId(teacher.getId());
        hw.setEndTime(DateUtils.parse(request.getParameter("endDate")));
        int tip = hwService.insert(hw);
        if (tip == 0) {
            msg = "布置作业成功啦！";
            hw = hwService.selectBy(hw);
            WebUtils.copyParamToBean(request.getParameterMap(), hwAttach);
            hwAttach.setHwId(hw.getId());
            hwAttach.setCreateMan(teacher.getName());
            hwAttach.setCreateTime(DateUtils.getDate());
            hwAttach.setTitle(request.getParameter("fileName"));
            tip = hwAttachService.insert(hwAttach);
            if (tip != 0) {
                msg = "布置作业的文件上传失败啦！";
                tip = 2;
            }
        }
        System.out.println(hw);
        System.out.println(hwAttach);
        map.put("tip", tip);
        map.put("msg", msg);
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        int tip = hwService.deleteById(id);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }

    protected void noSubmitPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        Student student = (Student) request.getSession().getAttribute("user");
        Integer id = student.getId();
        Page<Hw> page = hwService.hwNoSubmit(id, pageNo, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void submitPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        Student student = (Student) request.getSession().getAttribute("user");
        Integer id = student.getId();
        Page<Hw> page = hwService.hwSubmit(id, pageNo, pageSize);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void overduePage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        Student student = (Student) request.getSession().getAttribute("user");
        Integer id = student.getId();
        Page<Hw> page = hwService.hwOverdue(id, pageNo, pageSize);
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void hwOverTime(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        Teacher teacher = (Teacher) request.getSession().getAttribute("user");
        Integer id = teacher.getId();
        Page<Hw> page = hwService.hwOverTime(id, pageNo, pageSize);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void notComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        Integer id = Integer.valueOf(request.getParameter("content"));
        Page<HwStu> page = hwService.notComment(id, pageNo, pageSize);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void openComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        Integer id = Integer.valueOf(request.getParameter("content"));
        Page<HwStu> page = hwService.openComment(id, pageNo, pageSize);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void myPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        Teacher teacher = (Teacher) request.getSession().getAttribute("user");
        Integer id = teacher.getId();
        Page<Hw> page = hwService.myPage(id, pageNo, pageSize);
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }
}
